<template>
	<view class="container">
		<view class="tech-header">
			<view class="header-bg">
				<view class="tech-lines"></view>
				<view class="tech-dots"></view>
			</view>
			<text class="header-title">修改物品信息</text>
			<text class="header-subtitle">INVENTORY MANAGEMENT SYSTEM</text>
		</view>

		<view class="tech-card">
			<view class="card-header">
				<view class="card-icon">
					<uni-icons type="compose" size="24" color="#fff"></uni-icons>
				</view>
				<text class="card-title">物品信息编辑</text>
				<view class="card-line"></view>
			</view>

			<uni-forms ref="valiForm" :rules="rules" :modelValue="valiFormData" label-position="top">
				<uni-forms-item label-width="180rpx" label="分类" required name="category_id">
					<uni-data-select class="select" :arrayConfig="configParams" v-model="value" @change="change"
						:localdata="categoriesData" placeholder="请选择分类">
					</uni-data-select>
				</uni-forms-item>

				<uni-forms-item label-width="180rpx" label="物品图片" name="thumb">
					<view class="upload-section">
						<!-- 不使用插槽的自定义内容 -->
						<uni-file-picker v-model="imageFiles" file-mediatype="image" limit="1" mode="grid"
							showType="grid" :image-styles="imageStyles" :auto-upload="true" @success="uploadSuccess"
							@fail="uploadFail" title=" ">
						</uni-file-picker>
						<view class="upload-placeholder" v-if="!imageFiles || imageFiles.length === 0">
							<uni-icons type="camera" size="36" color="#3498db"></uni-icons>
							<text class="upload-text">点击上传图片</text>
						</view>
					</view>
				</uni-forms-item>

				<view class="form-row">
					<uni-forms-item label-width="180rpx" label="名称" required name="name">
						<uni-easyinput v-model="valiFormData.name" placeholder="请输入物品名称" />
					</uni-forms-item>

					<uni-forms-item label-width="180rpx" label="库存" required name="remain_count">
						<uni-easyinput v-model="valiFormData.remain_count" placeholder="请输入库存数量" type="digit" />
					</uni-forms-item>
				</view>

				<view class="form-row">
					<uni-forms-item label-width="180rpx" label="品牌" name="brand">
						<uni-easyinput v-model="valiFormData.brand" placeholder="请输入物品品牌" />
					</uni-forms-item>

					<uni-forms-item label-width="180rpx" label="型号" name="model">
						<uni-easyinput v-model="valiFormData.model" placeholder="请输入物品型号" />
					</uni-forms-item>
				</view>

				<uni-forms-item label-width="180rpx" label="描述" name="desc">
					<uni-easyinput v-model="valiFormData.desc" placeholder="请输入物品描述" />
				</uni-forms-item>

				<uni-forms-item label-width="180rpx" label="备注" name="note">
					<uni-easyinput v-model="valiFormData.note" placeholder="请输入备注信息" />
				</uni-forms-item>
			</uni-forms>

			<view class="action-buttons">
				<button class="submit-btn" @click="submit('valiForm')">保存修改</button>
				<button class="reset-btn" @click="resetForm">重置</button>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				uploading: false,
				configParams: {
					labelKey: "name",
					valueKey: "_id",
				},
				categoriesData: [],
				value: null,
				imageFiles: [],
				imageStyles: {
					height: 120,
					width: 120,
					border: {
						color: "#3498db",
						width: 1,
						style: "dashed"
					}
				},
				_id: null,
				valiFormData: {
					goods_id: null,
					category_id: null,
					name: '',
					brand: null,
					model: null,
					remain_count: null,
					desc: '',
					thumb: null, // 存储云文件ID
					is_on_sale: true,
					add_date: null,
					last_modify_date: null,
					note: ''
				},
				rules: {
					category_id: {
						rules: [{
							required: true,
							errorMessage: '请选择分类'
						}]
					},
					name: {
						rules: [{
							required: true,
							errorMessage: '名称不能为空'
						}]
					},
					remain_count: {
						rules: [{
								required: true,
								errorMessage: '不能为空'
							},
							{
								format: 'number',
								errorMessage: '只能输入数字'
							}
						]
					}
				},
			}
		},
		mounted() {
			this._id = uni.$router.params._id
			this.getCategoriesList()
		},
		methods: {
			// 获取物品信息
			async getGoods(_id) {
				try {
					const obj = uniCloud.importObject('goods')
					const res = await obj.getGoodsById({
						_id: _id
					})

					if (res.code === 0) {
						const goodsData = res.data;

						// 更新表单数据
						this.valiFormData = {
							...this.valiFormData,
							...goodsData
						};

						if (goodsData.thumb) {
							this.imageFiles = [{
								url: goodsData.thumb,
								type: 'image'
							}];
						}

						this.value = goodsData.category_id;
						this.valiFormData.category_id = goodsData.category_id;
					}
				} catch (error) {
					uni.showToast({
						title: '数据加载失败',
						icon: 'none'
					})
				}
			},
			// 获取分类列表
			async getCategoriesList() {
				try {
					const obj = uniCloud.importObject('goods')
					const res = await obj.getCategoriesList({})
					this.categoriesData = res.data.map(item => ({
						value: item._id,
						text: item.name
					}));
					if (this._id) {
						this.getGoods(this._id)
					}
				} catch (e) {
					uni.showToast({
						title: '分类加载失败',
						icon: 'none'
					})
				}
			},

			// 分类选择变化
			change(e) {
				if (e && e.value) {
					this.value = e.value
					this.valiFormData.category_id = e.value
				} else {
					this.value = null
					this.valiFormData.category_id = null
				}
			},

			// 修改图片上传成功处理
			uploadSuccess(e) {
				this.imageFiles = e.tempFiles || [];
				if (this.imageFiles.length > 0) {
					this.valiFormData.thumb = this.imageFiles[0].url;
				}
			},

			// 图片上传失败
			uploadFail(e) {
				uni.showToast({
					title: '图片上传失败',
					icon: 'none'
				})
			},
			// 生成云存储路径
			generateCloudPath(originalName) {
				const ext = originalName.split('.').pop()
				const timestamp = Date.now()
				const category_id = this.valiFormData.category_id
				return `goods/${category_id}/${timestamp}.${ext}`
			},
			// 提交表单
			async submit(ref) {
				try {
					await this.$refs[ref].validate()

					if (this.imageFiles.length > 0) {
						const file = this.imageFiles[0]
						if (file.url.startsWith('http://tmp')) {
							uni.showLoading({
								title: '图片上传中...',
								mask: true
							})
							
							try {
								const cloudPath = this.generateCloudPath(file.value.name)
								uniCloud.uploadFile({
									filePath: file.path || file.url,
									cloudPath,
									cloudPathAsRealPath: true
								}).then(res => {})
							} catch (error) {}
						}
					}
					this.valiFormData.remain_count = Number(this.valiFormData.remain_count)
					const submitData = {
						...this.valiFormData
					};

					delete submitData._id;
					delete submitData.goods_id;
					delete submitData.add_date;

					submitData.last_modify_date = Date.now();
					
					// 获取当前用户信息
					const userInfo = uni.getStorageSync('userInfo');
					submitData.operator = userInfo._id || 'system';
					submitData.operator_name = userInfo.username || userInfo.name || 'system';
					submitData.reason = '编辑物品库存';

					const obj = uniCloud.importObject('goods')
					const res = await obj.updateGoods({
						_id: this._id,
						data: submitData
					})

					if (res.code === 0) {
						uni.showToast({
							title: '提交成功',
							icon: 'success'
						})
						this.resetForm()
					}
				} catch (err) {
					let msg = err.errMsg?.includes('validate') ? '请检查表单填写' : '提交失败'
					uni.showToast({
						title: msg,
						icon: 'none'
					})
				}
			},

			// 重置表单
			resetForm() {
				this.valiFormData = {
					category_id: null,
					name: '',
					brand: null,
					model: null,
					remain_count: null,
					desc: '',
					thumb: null,
					is_on_sale: true,
					add_date: null,
					last_modify_date: null,
					note: ''
				}

				this.value = null
				this.imageFiles = []
				this.$refs.valiForm.clearValidate()
			}
		}
	}
</script>

<style lang="scss">
	page {
		background: linear-gradient(135deg, #f0f8ff 0%, #e6f7ff 100%);
		padding: 20rpx;
		font-family: 'Helvetica Neue', Arial, sans-serif;
	}

	.container {
		display: flex;
		flex-direction: column;
		min-height: 100vh;
	}

	.tech-header {
		position: relative;
		padding: 40rpx 0;
		text-align: center;
		margin-bottom: 30rpx;
		overflow: hidden;
		border-radius: 20rpx;
		background: linear-gradient(135deg, #3498db 0%, #1a5f9e 100%);
		box-shadow: 0 10rpx 30rpx rgba(52, 152, 219, 0.3);

		.header-bg {
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			overflow: hidden;
		}

		.tech-lines {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			background:
				linear-gradient(90deg, rgba(255, 255, 255, 0.1) 1px, transparent 1px),
				linear-gradient(0deg, rgba(255, 255, 255, 0.1) 1px, transparent 1px);
			background-size: 40rpx 40rpx;
			opacity: 0.5;
		}

		.tech-dots {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			background: radial-gradient(circle, rgba(255, 255, 255, 0.2) 2rpx, transparent 2rpx);
			background-size: 30rpx 30rpx;
		}

		.header-title {
			font-size: 42rpx;
			font-weight: bold;
			color: #fff;
			text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.2);
			position: relative;
			z-index: 2;
			letter-spacing: 2rpx;
		}

		.header-subtitle {
			display: block;
			font-size: 24rpx;
			color: rgba(255, 255, 255, 0.8);
			margin-top: 10rpx;
			letter-spacing: 4rpx;
			position: relative;
			z-index: 2;
		}
	}

	.tech-card {
		background: #fff;
		border-radius: 20rpx;
		padding: 40rpx;
		box-shadow: 0 10rpx 40rpx rgba(52, 152, 219, 0.15);
		margin-bottom: 40rpx;
		flex: 1;

		.card-header {
			display: flex;
			align-items: center;
			margin-bottom: 40rpx;
			position: relative;

			.card-icon {
				width: 60rpx;
				height: 60rpx;
				background: linear-gradient(135deg, #3498db 0%, #1a5f9e 100%);
				border-radius: 12rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				box-shadow: 0 5rpx 15rpx rgba(52, 152, 219, 0.3);
			}

			.card-title {
				font-size: 36rpx;
				font-weight: bold;
				color: #2c3e50;
				margin-left: 20rpx;
			}

			.card-line {
				position: absolute;
				bottom: -15rpx;
				left: 0;
				width: 120rpx;
				height: 6rpx;
				background: linear-gradient(90deg, #3498db, #1a5f9e);
				border-radius: 3rpx;
			}
		}
	}

	.upload-section {
		margin-top: 20rpx;
		position: relative;

		/* 修复文件选择器样式 */
		::v-deep .uni-file-picker {
			width: 100%;

			&__container {
				padding: 0;
			}

			&__header {
				display: none;
			}

			&__box {
				border: 2rpx dashed #3498db !important;
				border-radius: 16rpx;
				height: 200rpx;
				background-color: #f8fbff;
				transition: all 0.3s;
				display: flex;
				justify-content: center;
				align-items: center;
				position: relative;

				&:active {
					background-color: #e6f2ff;
				}
			}
		}

		.upload-placeholder {
			position: absolute;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			pointer-events: none;
			/* 允许点击穿透到文件选择器 */
			z-index: 2;

			.upload-text {
				font-size: 28rpx;
				color: #3498db;
				margin-top: 20rpx;
			}
		}
	}

	.form-row {
		display: flex;
		flex-wrap: wrap;
		margin: 0 -20rpx;

		.uni-forms-item {
			flex: 1 0 50%;
			padding: 0 20rpx;
			box-sizing: border-box;
			min-width: 300rpx;
		}
	}

	.action-buttons {
		display: flex;
		margin-top: 60rpx;
		gap: 30rpx;

		button {
			flex: 1;
			height: 90rpx;
			border-radius: 12rpx;
			font-size: 32rpx;
			font-weight: 500;
			display: flex;
			align-items: center;
			justify-content: center;
			transition: all 0.3s;
			box-shadow: 0 6rpx 20rpx rgba(52, 152, 219, 0.25);

			&::after {
				border: none;
			}
		}

		.submit-btn {
			background: linear-gradient(135deg, #3498db 0%, #1a5f9e 100%);
			color: white;

			&:active {
				transform: translateY(4rpx);
				box-shadow: 0 2rpx 10rpx rgba(52, 152, 219, 0.3);
			}
		}

		.reset-btn {
			background: #fff;
			color: #3498db;
			border: 2rpx solid #3498db;

			&:active {
				transform: translateY(4rpx);
				box-shadow: 0 2rpx 10rpx rgba(52, 152, 219, 0.2);
			}
		}
	}

	/* 表单元素样式调整 */
	.uni-forms-item__label {
		font-weight: bold;
		color: #2c3e50;
		margin-bottom: 10rpx;
		display: block;
	}

	.uni-easyinput {
		border: 2rpx solid #e0e0e0;
		border-radius: 12rpx;
		overflow: hidden;
		transition: all 0.3s;

		&:focus-within {
			border-color: #3498db;
			box-shadow: 0 0 10rpx rgba(52, 152, 219, 0.2);
		}
	}

	.uni-data-select {
		border: 2rpx solid #e0e0e0;
		border-radius: 12rpx;
		height: 80rpx;
		padding: 0 20rpx;

		&__input {
			height: 100%;
		}
	}
</style>